<template>
  <div ref="scroll" @scroll.passive="handleScroll" class="w-full h-full rounded-xl overflow-auto py-6 relative">
    <div v-masonry :fit-width="true" :origin-left="false" transition-duration="0.25s" item-selector=".grid-item"
      class="grid-container px-1 sm:px-0">
      <div v-if="list.length === 0">
        <div class="grid-item" v-for="i in 10" :key="i">
          <Skeleton></Skeleton>
        </div>
      </div>
      <div v-masonry-tile class="grid-item" v-for="video in list" :key="video">
        <VideoCard :videoInfo="video"></VideoCard>
      </div>
    </div>
  </div>
</template>

<script setup>
import VideoCard from "@/components/VideoCard.vue";
import {
  getCurrentInstance,
  onUpdated,
  ref,
  reactive,
  onMounted,
  onUnmounted,
} from "vue";
import { getVideoPageListAPI } from "@/http/api/video";
import { useRoute } from "vue-router";
import _debounce from "lodash/debounce";
const { appContext } = getCurrentInstance();

let list = ref([]);

const route = useRoute();

let page = 1;
let scrollFlag = true;

getVideoPageListAPI({
  page: page,
  type: route.params.channelId,
}).then((res) => {
  if (res.code === 200 && res.data) {
    list.value = list.value.concat(res.data);
  }
});

let scroll = ref(null);
const handleScroll = _debounce(() => {
  let scrollBottom =
    scroll.value.scrollHeight -
    scroll.value.scrollTop -
    scroll.value.clientHeight;
  if (scrollBottom < 100) {
    // 执行加载动画

    //获取下一页视频
    if (!scrollFlag) {
      ElMessage({
        message: "已到尾部啦！^ ^",
        type: "warning",
      });
      return;
    }
    getVideoPageListAPI({
      page: ++page,
      type: route.params.channelId,
    }).then((res) => {
      if (res.code === 200) {
        if (!res.data) {
          scrollFlag = false;
          ElMessage({
            message: res.message,
            type: "warning",
          });
          return;
        }
        list.value = list.value.concat(res.data);
      }
    });

    //取消加载动画
  }
}, 500);

onUpdated(() => {
  setTimeout(() => {
    appContext.config.globalProperties.$redrawVueMasonry();
    console.log("redraw");
  }, 1000);
});
</script>

<style lang="scss" scoped>
.grid-container {
  width: 100%;
  margin: 0 auto;

  .grid-item {
    border-radius: 0.75rem;
    width: clamp(10rem, 45vw, 15rem);
    margin: 0 1rem 1rem 0;
  }
}
</style>